package org.guegan.util.dircompare.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class FileToMd5 implements FileToSignature {

	private static int MAX = (int) Math.pow(2, 16);
	private MessageDigest digest = null;
	
	private MessageDigest getDigest() {
		if (digest == null) {
			try {
				digest = MessageDigest.getInstance("MD5");
			}
			catch (NoSuchAlgorithmException ex) {
			}
		}
		return digest;
	}

	public String calculate(File file) {
		String ret = null;
		if (file.isFile()) {
			boolean exOccured = false;
			getDigest().reset();
			FileInputStream stream = null;
			try {
				stream = new FileInputStream(file);
				DigestInputStream digestStr = new DigestInputStream(stream, digest);
				byte[] input = new byte[MAX];
				while (digestStr.read(input) != -1);
				digestStr.close();
			}
			catch (FileNotFoundException ex) {
				exOccured = true;
			}
			catch (IOException ex) {
				exOccured = true;
			}
			finally {
				if (stream != null) {
					try {
						stream.close();
					}
					catch (IOException ex) {
					}
				}
			}
			if (!exOccured) {
				ret = ByteToHexString.toHex(digest.digest());
			}
		}
		return ret;
	}
	
	public String calculate(String data) {
		String ret = null;
		getDigest().reset();
		digest.update(data.getBytes());
		ret = ByteToHexString.toHex(digest.digest());
		return ret;
	}

}
